<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\UserRequest;
use App\Http\Resources\UserResource;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class UserController extends Controller
{
    //获取用户信息
    public function index(Request $request)
    {
        return successReturn(new UserResource($request->user()));
    }


    //注册
    public function store(UserRequest $request)
    {
        //验证码是否正确
        if (!checkLoginSms($request->get('phone'), $request->get('code'), 'register')) {
            return failReturn('验证码错误');
        }
        //手机号是否已经注册
        if (User::query()->where('phone', $request->get('phone'))->exists()) {
            return failReturn('手机号已注册');
        }
        //注册
        $user = User::query()->create([
            'phone' => $request->get('phone'),
            'nickname' => '江西盟造.' . Str::random(10),
            'avatar' => '',
            'password' => Hash::make($request->get('password')),
        ]);
        $token = auth('api')->login($user);
        return app(AuthorizationsController::class)->responseWithToken($token);
    }


    //忘记密码
    public function password(UserRequest $request)
    {
        //验证码是否正确
        if (!checkLoginSms($request->get('phone'), $request->get('code'), 'reset_password')) {
            return failReturn('验证码错误');
        }
        //手机号是否已经注册
        $user = User::query()->where('phone', $request->get('phone'))->first();
        if (!$user) {
            return failReturn('手机号未注册');
        }
        $user->password = Hash::make($request->get('password'));
        $user->save();
        return successReturn('密码修改成功');
    }


    //修改个人码信息
    public function edit(Request $request)
    {
        $user = $request->user();

        if ($request->get('nickname') && $user->nickname != $request->get('nickname')) {
            $user->nickname = $request->get('nickname');
        }
        if ($request->get('avatar') && $user->avatar != $request->get('avatar')) {
            $user->avatar = $request->get('avatar');
        }
        if ($user->isDirty()) {
            $user->save();
        }
        return successReturn('修改成功');
    }

}
